package com.yiwyn.example;


import lombok.extern.slf4j.Slf4j;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;

@Slf4j
// @Warmup(iterations = 1, time = 1)
@Measurement(iterations = 5, time = 1)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(value = 2)
@State(Scope.Thread)
public class StringTest {


    // @Benchmark
    public String stringTest() {
        String a = "";
        for (int i = 0; i < 1000; i++) {
            a += i;
        }
        return a;
    }

    @Benchmark
    public String stringBuildTest() {
        StringBuilder a = new StringBuilder();
        for (int i = 0; i < 1000; i++) {
            a.append(i);
        }
        return a.toString();
    }

    // @Benchmark
    public String stringBuildLogTest() {
        StringBuilder a = new StringBuilder();
        for (int i = 0; i < 1000; i++) {
            log.info("当前数字:{}", i);
            a.append(i);
        }
        return a.toString();
    }


    private int a = 10;
    private int b = 20;


    // @Benchmark
    // @Warmup(iterations = 4, time = 2, timeUnit = TimeUnit.SECONDS)
    public Integer jitTest() {
        return complexCalculation(a, b);
    }

    // @Benchmark
    // @Warmup(iterations = 4, time = 2, timeUnit = TimeUnit.SECONDS)
    // @Warmup(iterations = 0)
    public Integer jitTest1() {
        return complexCalculation(a, b);
    }


    // 一个可被JIT优化的复杂计算方法
    private int complexCalculation(int x, int y) {
        int result = 0;
        // 循环计算（JIT可能会展开循环或优化计算逻辑）
        for (int i = 0; i < 10000; i++) {
            result += (x * y + i) % (x + y + (i % 3));
        }
        return result;
    }


    public static void main(String[] args) throws RunnerException {
        Options options = new OptionsBuilder()
                .include(StringTest.class.getSimpleName())
                // .addProfiler(GCProfiler.class)
                // .jvmArgs("-XX:+PrintCompilation")
                .build();

        new Runner(options).run();
    }
}
